// 服务端文件
import * as net from 'net';
import * as readline from 'readline';
import * as util from "./util";
import { default as SocketService } from "./server/SocketService";
import { default as ConsoleService } from "./server/ConsoleService";
import * as Service from "./server/Service";

Service.server.value = net.createServer((socket) => {
    socket.on('data', (dataBuffer) => {
        let dataString = dataBuffer.toString();
        let data: util.RequestMessage<any> | null = null;
        try {
            data = JSON.parse(dataString);
        } catch (e) {
            socket.write(util.INVALID_COMMAND_MESSAGE)
        }
        data = (data as util.RequestMessage<any>)
        let handle = false
		for (let key in SocketService) {
			let func = SocketService[key]
			if (util.isSocketHandleMethodRequest(func)) {
				if (data.command === func.command) {
					func(socket, data.data)
					handle = true
				}
			}
		}
        if (!handle) {
            socket.write(util.INVALID_COMMAND_MESSAGE)
        }
    });

    socket.on('error', (e) => {
		for (let key in SocketService) {
			let func = SocketService[key]
			if (util.isSocketHandleMethodRequest(func)) {
				if (func.onError) {
					func(socket, null)
				}
			}
		}
    })

    socket.on('end', () => {
		for (let key in SocketService) {
			let func = SocketService[key]
			if (util.isSocketHandleMethodRequest(func)) {
				if (func.onEnd) {
					func(socket, null)
				}
			}
		}
    })

    socket.on('close', () => {
		for (let key in SocketService) {
			let func = SocketService[key]
			if (util.isSocketHandleMethodRequest(func)) {
				if (func.onClose) {
					func(socket, null)
				}
			}
		}
    })
})

Service.server.value.listen(5000, () => {
    util.logInConsole('聊天室已启动，监听端口 5000');
});

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', (input) => {
    let command = input.trim()
    if (command.length === 0) {
        return;
    }
    let commandData = util.parseCommand(command)
    let handle = false
    for (let key in ConsoleService) {
        let func = ConsoleService[key]
        if (func.command === commandData.command) {
            func(commandData)
            handle = true
            break
        }
    }
    if (!handle) {
        util.logInConsole('未知命令')
    }
});